<?php
/**
 * Registered.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2019/6/10
 * Time: 10:55
 */
namespace app\api\open\member;

use app\api\model\MemberModel;
use app\api\open\Base;
use think\Validate;

class Registered extends Base
{
    protected $username = "";
    protected $password = "";

    protected $type = "0";
    protected $memberData = [];

    /**
     * Login constructor.
     * @param array $param
     * @throws \Exception
     */
    public function __construct($param=[])
    {
        parent::__construct($param);

        $param = $this->params;

        $validate = new Validate([
            "username" => "require",
            "password" => "require|min:6",
            "re_password" => "require|min:6"
        ],[
            "username.require" => "用户名必填",
            "password.require" => "密码必填",
            "password.min" => "密码至少6位以上",
            "re_password.require" => "重复密码必填",
            "re_password.min" => "重复密码至少6位以上"
        ]);

        if($validate->check($param) === false) {
            throw new \Exception($validate->getError(),1);
        }

        // 验证两次密码是否一致？
        if($param['password'] !== $param['re_password'])
        {
            throw new \Exception("两次密码不一致",1);
        }

        // 注册方式
        if(isset($param['type']) && $param['type'] == '1')
        {
            // 短信注册方式
            $this->type = "1";
            // 电话
            $this->memberData['phone'] = $param['username'];
        }
        else if(isset($param['type']) && $param['type'] == '2')
        {
            // 邮箱注册方式
            $this->type = "2";
            // 邮箱
            $this->memberData['email'] = $param['username'];
        }
        else
        {
            // 默认注册方式
            $this->type = "0";
        }

        // 用户名
        $this->username = $param['username'];
        $this->memberData['username'] = $param['username'];
        // 是否启用(0:否,1:是)
//        $this->memberData['status'] = 1;
        // 加密密码
        $this->password = $param['password'];
        $this->memberData['password'] = md5(md5($this->password));
    }

    /**
     * @param array $param
     * @return array|mixed|object|string
     * @throws \Exception
     */
    public function index($param=[])
    {
        $info = MemberModel::getInstance()->get(['username'=>$this->username],['field'=>'id']);
        if(empty($info['id'])){
            $member_id = MemberModel::getInstance()->save(null,$this->memberData);
        }else{
            throw new \Exception("系统已经存在该会员",2);
        }
        // 自动登录
        return (new Login(['username'=>$this->username,'password'=>$this->password]))->signIn();
    }
}